package com.xinqi.xinqidev.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinqi.xinqidev.mapper.UserMapper;
import com.xinqi.xinqidev.pojo.entity.User;
import com.xinqi.xinqidev.pojo.result.Result;
import com.xinqi.xinqidev.pojo.result.ResultUtil;
import com.xinqi.xinqidev.service.UserService;
import com.xinqi.xinqidev.utils.UserHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @author xin麒
 * @date 2023/12/29 23:19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {



    @Override
    public Result login(User user, HttpSession session) {
        String username = user.getUsername();
        if (username == null || username.length() == 0) return ResultUtil.fail("用户名称不可为空");

        String password = user.getPassword();

        if (password == null || password.length() == 0) return ResultUtil.fail("用户密码不可为空");


        log.debug("user is " + user);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username)
                .eq("password", password);
        User aUser = getOne(queryWrapper);

        if (aUser == null) return ResultUtil.fail("该用户不存在！");

        session.setAttribute("user", username);
        session.setAttribute("userId", aUser.getId().toString());
        if (UserHolder.getUser(aUser.getId()) != null) return ResultUtil.fail("该用户须退出方能登录");

        UserHolder.addUser(aUser.getId());

        return ResultUtil.ok("登录成功");
    }
}
